//
//  DAFileListViewController.m
//  DAKnowledge
//
//  Created by DACadmin on 16/7/7.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAFileListViewController.h"
#import "DAHeader.h"
#import "DAUserFileModel.h"
#import "DAFileListTableViewCell.h"
#import "DAWebFileViewController.h"

@interface DAFileListViewController () <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchControllerDelegate>{
    UIView *statusCover;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *keys; //存储key值
@property (nonatomic, strong) NSMutableArray *indexArray; //索引数组
@property (nonatomic, strong) NSMutableArray *charactorArray; //A-Z 数组

@property (nonatomic, strong) NSMutableArray *searchResults;

@property (nonatomic, strong) NSMutableDictionary *userDic;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;

@property (weak, nonatomic) IBOutlet UIView *searchBarBackView;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *searchDisplayController;

@end

@implementation DAFileListViewController
 int i = 0;
 NSMutableArray *dataArray;
- (void)viewDidLoad {
    [super viewDidLoad];
    dataArray = [[NSMutableArray alloc]init];
    [self creatTableView];
    [self searchSetting];
    [self.tableView.mj_header beginRefreshing];
   //  Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 搜索
- (void)searchSetting{
    self.searchBar.backgroundImage = [self imageWithColor:[UIColor colorWithHexString:backGroundColor] size:self.searchBar.bounds.size];
    NSString *search = NSLocalizedString(@"input keywords for searching", nil);
   // NSString *searchKey = [NSString stringWithFormat:@"搜索%@的文件",self.name];
    self.searchBar.placeholder = search;
    self.searchBar.delegate = self;
    self.searchDisplayController.delegate = self;
    UITextField *text = [self.searchBar valueForKey:@"_searchField"];
    [text setValue:[UIFont systemFontOfSize:12] forKeyPath:@"_placeholderLabel.font"];
    self.searchBarBackView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    
    [self.searchBar setTintColor:[UIColor whiteColor]];
    [[[[self.searchDisplayController.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self.searchDisplayController.searchBar setBackgroundColor:[UIColor supportGreenColor]];
    statusCover = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 20)];
    statusCover.backgroundColor = [UIColor supportGreenColor];
    [self.view addSubview:statusCover];
    [self.searchBar setTintColor:[UIColor whiteColor]];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.searchDisplayController.searchBar setBackgroundColor:[UIColor colorWithHexString:backGroundColor]];
    [statusCover removeFromSuperview];
    [self.searchBar setTintColor:[UIColor darkGrayColor]];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(nullable NSString *)searchString{
    [self.searchResults removeAllObjects];
    //    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"self contains[cd] %@", self.searchController.searchBar.text];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fileName contains[cd] %@", self.searchBar.text];
    self.searchResults = [[dataArray filteredArrayUsingPredicate:predicate]mutableCopy];
    NSLog(@"Search %@", self.searchResults);
    
    //  [self.tableVIew reloadData];
    [self.searchDisplayController.searchResultsTableView reloadData];
    
    return YES;
}
- (void)searchDisplaycontroller:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}
- (void)dealloc{
    self.tableView.delegate = nil;
    self.searchBar.delegate = nil;
}
//searchBar  背景色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
    CGRect rect = CGRectMake(0, 20, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - 索引数组
- (void)arraySort{
    self.keys = [NSMutableArray array];
    self.indexArray = [NSMutableArray array];
    self.userDic = [NSMutableDictionary dictionary];
    self.charactorArray = [NSMutableArray array];
    for (char a = '0'; a <= '9'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c",a]];
    }
    for (char a = 'A'; a <= 'Z'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c",a]];
    }
    for (DAUserFileModel *userFileModel in dataArray) {
        NSString *key = [self firstCharactor:userFileModel.fileName];
        [self.keys addObject:key];
    }
    for (NSString *key in self.keys) {
        NSMutableArray *arr = [NSMutableArray array];
        [self.userDic setObject:arr forKey:key];
    }
    for (DAUserFileModel *userFileModel in dataArray) {
        NSString *key = [self firstCharactor:userFileModel.fileName];
        //NSLog(@"file名 %@",userFileModel.fileName);
        [self.userDic[key] addObject:userFileModel];
    }
    self.indexArray = [[self.userDic.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]mutableCopy];
    if ([self.indexArray containsObject:@"#"]) {
        [self.indexArray removeObject:@"#"];
        [self.indexArray addObject:@"#"];
    }
}
// 获取首字母方法
- (NSString *)firstCharactor:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, YES);
    NSString *largeStr = [str capitalizedString];
    NSString *firstStr;
    if (string.length != 0) {
        firstStr = [largeStr substringToIndex:1];
    }
    BOOL isContain = [self.charactorArray containsObject:firstStr];
    if (isContain == NO || [firstStr isEqualToString:@""]) {
        firstStr = @"#";
    }
    return firstStr;
}
#pragma mark - 创建TableView
- (void)creatTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    [self prepareFileData];
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tableView.sectionIndexColor = [UIColor supportGreenColor];
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.searchDisplayController.searchResultsTableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.searchDisplayController.searchResultsTableView.tableFooterView = [UIView new];
    //
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld@3x", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld@3x", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21@3x"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
}

- (void)refreshData{
    [self prepareFileData];
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
}
#pragma mark -  准备数据
- (void)prepareFileData{
    NSString *url = DAUserFileURL;
    NSDictionary *dic = @{@"userID":self.ID};
    NSLog(@"User ID %@ ",self.ID);
    [self dataHandelWithUrl:url parame:dic];
}

- (void)dataHandelWithUrl:(NSString *)url parame:(NSDictionary *)dic{
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        [weakSelf dataTransFormModel:result[@"result"]];
    }];
}
- (void)dataTransFormModel:(NSArray *)resultArray{
    DAUserFileModel *userFileModel = [[DAUserFileModel alloc]init];
    NSArray *array = [userFileModel returnModelInArrayWithDic:resultArray];
    
    dataArray = [NSMutableArray array];
    [dataArray addObjectsFromArray:array];
    
    
    [self.tableView reloadData];
    
    [self arraySort];
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchDisplayController.active) {
        return 1;
    }else{
        return self.indexArray.count;
    }
}

//索引内容
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if (tableView == self.tableView) {
        return self.indexArray;
    }else{
        return nil ;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        return [self.indexArray objectAtIndex:section];
    }else{
        return nil;
    }
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
    if (dataArray != nil && tableView == self.tableView) {
        NSString *key = self.indexArray[section];
        NSArray *arr = [self.userDic objectForKey:key];
        return [arr count];
    }else{
        return [self.searchResults count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView ) {
        DAFileListTableViewCell *fileListCell = [tableView dequeueReusableCellWithIdentifier:@"file_Cell"];
        if (fileListCell == nil) {
            fileListCell = [[DAFileListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"file_Cell"];
        }
    
        NSString *key = self.indexArray[indexPath.section];
        NSArray *arr = [self.userDic objectForKey:key];
        //CELL属性设置
        DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
        //UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"file_%@.png",model.fileType]];
        //fileListCell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
        NSString *file = [NSString stringWithFormat:@"file_%@.png",model.fileExtend];
        UIImage *image = [UIImage imageNamed:file];
        fileListCell.fileNameLabel.text = model.fileName;
        fileListCell.fileImageView.image = image;
        fileListCell.fileIntroduction.text = model.fileType;
        fileListCell.fileIntroduction.textColor = [UIColor colorWithHexString:timeColor];
        
        //处理文件大小
        int fileSize = [model.fileSize intValue];
        float fileSizeK = 0.0;
        float fileSizeM = 0.0;
        if (fileSize > 999 && fileSize < 999*1024) {
            fileSizeK = fileSize/1024.0;
            fileListCell.fileSize.text = [NSString stringWithFormat:@"%.2fK",fileSizeK];
        }else if (fileSize >= 999*1024 ){
            fileSizeM = fileSize/(1024.0*1024.0);
            fileListCell.fileSize.text = [NSString stringWithFormat:@"%.2fM",fileSizeM];
        }else{
            fileListCell.fileSize.text = [NSString stringWithFormat:@"%dB",fileSize];
        }
        fileListCell.fileSize.textColor = [UIColor colorWithHexString:timeColor];
        return fileListCell;
    }else{
        DAFileListTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"SearchCell"];
        if (cell == nil) { //需要在storyBoard里新拖一个Cell
            cell = [[DAFileListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SearchCell"];
        }
        if (self.searchResults.count > 0) {
        cell.userFileModel = self.searchResults[indexPath.row];
        
        DAUserFileModel *model = [self.searchResults objectAtIndex:indexPath.row];
        NSString *file = [NSString stringWithFormat:@"file_%@.png",model.fileExtend];
        UIImage *image = [UIImage imageNamed:file];
        cell.fileNameLabel.text = model.fileName;
        cell.fileImageView.image = image;
        cell.fileIntroduction.text = model.fileType;
        cell.fileIntroduction.textColor = [UIColor colorWithHexString:timeColor];
        
        int fileSize = [model.fileSize intValue];
        float fileSizeM = 0.0;
        float fileSizeK = 0.0;
        if (fileSize >999 && fileSize < 999*1024) {
            fileSizeK = fileSize/1024.0;
            cell.fileSize.text = [NSString stringWithFormat:@"%.2fK",fileSizeK];
        }else if(fileSize >= 999*1024){
            fileSizeM = fileSize/(1024.0*1024.0);
            cell.fileSize.text = [NSString stringWithFormat:@"%.2fM",fileSizeM];
        }else{
            cell.fileSize.text = [NSString stringWithFormat:@"%dK",fileSize];
        }

        cell.fileSize.textColor = [UIColor colorWithHexString:timeColor];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //cell.backgroundColor = [UIColor redColor];
        return cell;
        
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    view.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 100, 10)];
    label.text = [self.indexArray objectAtIndex:section];
    label.font = [UIFont boldSystemFontOfSize:14];
    label.textColor = [UIColor darkGrayColor];
    [view addSubview:label];
    return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
    
    NSString *key = self.indexArray[indexPath.section];
    NSArray *arr = [self.userDic objectForKey:key];
    DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
    webFile.fileUrl = model.fileUrl;
    webFile.fileName = model.fileName;
    webFile.fileExtend = model.fileExtend;
    webFile.fileUrl = @"URL";
   // webFile.fileName = model.filename;
    webFile.fileName = @"FILE_NAME";
    webFile.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webFile animated:YES];
}

#pragma mark - 解决UISearchDisplayController searchResultsTableView 的ContentSize bug
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
